import { join } from 'path';
import { app, BrowserWindow, globalShortcut, session } from 'electron';
import Shortcut from './lib/globalShortcut';
import { existsSync, rmSync } from 'fs';
import { checkForUpdates } from './lib/auto-update';
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';

export const ROOT_PATH = {
  // /dist
  dist: join(__dirname, '../dist'),
  // /dist or /public
  public: join(__dirname, app.isPackaged ? '../dist' : '../public')
};

let win: BrowserWindow | null;

// Here, you can also use other preload
// const preload = join(__dirname, './preload.js')
const url = process.env.VITE_DEV_SERVER_URL as string;

async function createWindow() {
  win = new BrowserWindow({
    show: false,
    width: 950,
    height: 600,
    minWidth: 950,
    minHeight: 600,
    frame: false, // 去掉边框
    icon: join(ROOT_PATH.public, 'favicon.ico'), //需要ico图标，否则无法显示图标
    webPreferences: {
      contextIsolation: false,
      nodeIntegration: true,
      webSecurity: false,
      plugins: true,
      sandbox: false

      //   preload,
    }
  });

  require('@electron/remote/main').initialize();

  require('@electron/remote/main').enable(win.webContents);

  if (app.isPackaged) {
    win.loadFile(join(ROOT_PATH.dist, 'index.html'));
  } else {
    win.webContents.openDevTools();
    win.loadURL(url);
    await session.defaultSession.loadExtension(join(process.cwd(), 'Vue Devtools'));
  }

  // 页面加载完成再显示
  win.once('ready-to-show', () => {
    win?.show();
    if (app.isPackaged) {
      checkForUpdates();
    }
  });
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    win = null;
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

app.on('ready', async () => {
  const gotTheLock = app.requestSingleInstanceLock();
  if (gotTheLock) {
    const userData = app.getPath('userData');

    const tempPath = join(app.isPackaged ? userData : process.cwd(), '.markdown-k', 'temp', 'images');
    existsSync(tempPath) && rmSync(tempPath, { recursive: true });
  }

  createWindow();
});

if (!app.isPackaged) {
  if (process.platform === 'win32') {
    process.on('message', data => {
      if (data === 'graceful-exit') {
        app.quit();
      }
    });
  } else {
    process.on('SIGTERM', () => {
      app.quit();
    });
  }
}

// 修改通知时app名称
app.setAppUserModelId('markdown_k');

//监听失去焦点事件,注销快捷键
app.on('browser-window-blur', () => {
  globalShortcut.unregisterAll();
});
//监听获得焦点事件,注册快捷键
app.on('browser-window-focus', () => {
  Shortcut();
});
